package com.ketangpai.admin.service.impl;

import com.ketangpai.admin.entity.User;
import com.ketangpai.admin.entity.WorkComment;
import com.ketangpai.admin.mapper.UserMapper;
import com.ketangpai.admin.mapper.WorkCommentMapper;
import com.ketangpai.admin.service.WorkCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WorkCommentServiceImpl implements WorkCommentService {
    @Autowired
    private WorkCommentMapper workCommentMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> getCommentsList(Integer workId, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<WorkComment> comments = workCommentMapper.selectMainComments(workId, offset, pageSize);
        int total = workCommentMapper.countMainComments(workId);

        // 获取每个主评论的用户信息和回复
        for (WorkComment comment : comments) {
            User user = userMapper.selectById(comment.getUserId());
            comment.setUsername(user.getName());
            comment.setUserAvatar(user.getAvatar()); // 添加这行，设置用户头像

            List<WorkComment> replies = workCommentMapper.selectReplies(comment.getId());
            // 设置回复的用户信息
            for (WorkComment reply : replies) {
                User replyUser = userMapper.selectById(reply.getUserId());
                reply.setUsername(replyUser.getName());
                reply.setUserAvatar(replyUser.getAvatar()); // 添加这行，设置回复用户头像
            }
            comment.setReplies(replies);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("list", comments);
        result.put("total", total);
        return result;
    }


    @Override
    public void addComment(WorkComment comment) {
        comment.setCommentTime(LocalDateTime.now());
        workCommentMapper.insert(comment);
    }

    @Override
    public void addReply(Integer parentId, String replyTo, WorkComment reply) {
        // 设置回复相关信息
        reply.setParentId(parentId);
        reply.setReplyTo(replyTo);
        // 保存回复
        workCommentMapper.insert(reply);
    }
    // WorkCommentServiceImpl.java
    @Override
    public List<WorkComment> getReplies(Integer commentId) {
        List<WorkComment> replies = workCommentMapper.selectReplies(commentId);

        // 为每个回复设置用户信息
        for (WorkComment reply : replies) {
            User user = userMapper.selectById(reply.getUserId());
            reply.setUsername(user.getName());
            reply.setUserAvatar(user.getAvatar());
        }

        return replies;
    }

    @Override
    public void deleteComment(Integer commentId) {
        // 物理删除）
        workCommentMapper.deleteById(commentId);
    }
}
